package sale_admin

import (
	"context"
	"encoding/json"
	"sale-admin/config/mysql"
	"sale-admin/internal/app/grpc/protoc/sale_adminc"
	"sale-admin/internal/app/web/schema"
	"sale-admin/internal/dal"
	"sale-admin/internal/dao"
	"sale-admin/internal/define"
	"sale-admin/internal/models"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/helper"
	"192.168.1.75/go-pkg/logx"
	"gorm.io/gorm"
)

// CreateOnlineOrder 创建在线订单
// 包括活动订单和快递到家订单
func (s SaleAdminService) CreateOnlineOrder(ctx context.Context, req *sale_adminc.CreateOnlineOrderReq) (*sale_adminc.CreateOnlineOrderRsp, error) {
	rsp := &sale_adminc.CreateOnlineOrderRsp{}
	db := mysql.NewDB()
	if len(req.List) <= 0 {
		rsp.Code = -1
		rsp.Msg = "订单信息不能为空"
		return rsp, errorx.New("订单信息不能为空", -1)
	}
	// 创建订单
	logx.Info(context.Background(), "CreateOnlineOrder", logx.Any("req", req))
	db.Transaction(func(tx *gorm.DB) error {
		for _, record := range req.List {
			goodsDetail, _ := dao.Goods{}.Detail(ctx, dal.Use(tx), record.GoodsId)
			GoodsData := []schema.OrderGoodsDetailOld{
				{
					GoodsName: goodsDetail.GoodsName1,
					Univalent: record.Univalent,
					GoodsID:   goodsDetail.GoodsID,
				},
			}
			goodsDataBytes, _ := json.Marshal(GoodsData)
			// salesID
			salesID := ""
			if record.RobotID != "" {
				robotDetail, _ := dao.Robot{}.Detail(ctx, dal.Use(tx), record.RobotID, "")
				if robotDetail != nil {
					salesID = robotDetail.SalesID
				}
			}
			// 零售订单不支持单个订单记录多个数量，故多个商品的，拆分为多个子单
			for i := 0; i < int(record.Count); i++ {
				childOutTradeNo := ""
				if record.Count == 1 {
					childOutTradeNo = record.ChildOutTradeNo
				} else {
					childOutTradeNo, _ = helper.UUID{}.String()
				}
				err := tx.WithContext(ctx).Model(&models.MaOrder{}).Create(&models.MaOrder{
					RobotName:       record.RobotID,
					SalesID:         salesID,
					OutTradeNo:      req.OutTradeNo,
					EndOutTradeNo:   req.OutTradeNo,
					ChildOutTradeNo: childOutTradeNo,
					GoodsID:         record.GoodsId,
					PaymentAmount:   record.Univalent,
					ActualAmount:    record.Univalent,
					CountData:       string(goodsDataBytes),
					OrderSource:     1,                                        // 线上
					OrderStatus:     int(define.OrderStatus_Shipment_Pending), // 待发货
				}).Error
				if err != nil {
					return err
				}
			}
		}
		// 订单收货地址信息
		_, err := dao.OrderUserAddress{}.Create(ctx, mysql.NewDB(), models.OrderShipmentInfo{
			OutTradeNo:    req.OutTradeNo,
			ExpressFee:    req.ExpressFee,
			UserName:      req.UserAddress.UserName,
			TelNumber:     req.UserAddress.TelNumber,
			PostalCode:    req.UserAddress.PostalCode,
			ProvinceName:  req.UserAddress.ProvinceName,
			CityName:      req.UserAddress.CityName,
			CountyName:    req.UserAddress.CountyName,
			StreetName:    req.UserAddress.StreetName,
			DetailAddress: req.UserAddress.DetailAddress,
		})
		if err != nil {
			return err
		}
		return nil
	})
	return rsp, nil
}
